const { createApp, ref, reactive, onMounted, watch } = Vue;
const app = createApp({
    setup() {
        //图片路径
        const imageUrl = ref('')
        //新闻类型
        let newsType = ref([

        ])
        //新闻类型流水号
        let categoryNum = ''

        //需要提交的值
        const form = reactive({})
        let editor1 = reactive({});
        // 监听
        // watch(() => form, (newValue, oldValue) => {

        // })
        //         watch(() => form, (newValue, oldValue) => {

        // });
        //新闻分类
        const typeChange = (res) => {
            console.log(res);
            categoryNum = res
            // 查询表名获取类别编号
            $.ajax({
                headers: {
                    "content-type": "application/x-www-form-urlencoded",
                },
                url: "https://service.essp.top/apiForMoHe/generalBusiness/generalQueryByTableNameWithOriginal",
                method: "post",
                data: {
                    Data: "news_category", //表名
                    // Condition: `Parent_SerialNumber='${res}'`,
                    Condition: "",
                },
                success: (res) => {
                    newsType.value = res
                    console.log('news_category', newsType.value);
                    categoryNum = res[0].News_Category_SerialNumber
                },
                error: (err) => {
                    console.log(err)
                },
            });
        }
        //查询新闻类别树
        const queryTree = () => {
            $.ajax({
                headers: {
                    "content-type": "application/json",
                },
                url: "https://service.essp.top/apiForMoHe/generalBusiness/getNewsCategoryTree",
                method: "get",
                data: {
                    News_Categeroy_SerialNumber: "",
                },
                success: (res) => {
                    console.log('查询结果', res);
                    newsType.value = res
                    console.log('news_category', newsType.value);
                    categoryNum = res[0].News_Category_SerialNumber
                    console.log('news_categorycategoryNum', newsType.value);
                },
                error: (err) => {
                    console.log(err)
                },
            });
        }
        // 页面加载就调用函数
        onMounted(() => {
            // 获取 URL 参数
            const urlParams = new URLSearchParams(window.location.search);
            const Obtainaction = urlParams.get('action');
            const obtainNewsSerialNumber = urlParams.get('ObtainNews_SerialNumber');
            console.log('Action:', Obtainaction);
            console.log('ObtainNewsSerialNumber:', obtainNewsSerialNumber);
            init();
            queryTree()
            if (Obtainaction == "Add") {
                console.log('执行添加新闻逻辑');

            } else if (Obtainaction == "Modify") {
                console.log('执行编辑新闻逻辑');
                EditNews()
            }
        })
        const init = () => {
            const that = this;
            const { createEditor, createToolbar } = window.wangEditor;
            const editorConfig = {
                placeholder: '请输入内容',
                MENU_CONF: {
                    uploadImage: {
                        async customUpload(file, insertFn) {
                            new Compressor(file, {
                                quality: 1,
                                success(file) {
                                    const formData = new FormData();
                                    formData.append("file", file, file.name);
                                    let oFileReader = new FileReader();
                                    oFileReader.readAsDataURL(file);
                                    oFileReader.onload = function (e) {
                                        console.log(e);
                                        console.log(e.currentTarget.result);
                                        console.log(file.lastModified);
                                        let uid = file.lastModified;
                                        let url = e.currentTarget.result;
                                        let img = new Object();
                                        img.uid = uid;
                                        img.url = url;
                                        let imgArry = new Array();
                                        imgArry.push(img);
                                        console.log(imgArry);
                                        let base64Image = url;
                                        let dataIndex = base64Image.indexOf("data:");
                                        let base64Index = base64Image.indexOf(";base64,");
                                        let substring = base64Image.substring(
                                            dataIndex + 5,
                                            base64Index
                                        );
                                        let ls_split = substring.split("/");
                                        let URL = uid + "." + ls_split[1];
                                        console.log(URL);
                                        $.ajax({
                                            // url: `${BASE_URL2}/generalBusiness/generalSaveFilesAsImage`,
                                            url: "https://service.kdddy.cn/donghuiForRequest/store/photo",
                                            // url: "http://10.1.0.217:8087/store/photo",
                                            type: "POST",
                                            contentType: "application/json", // 设置请求体的媒体类型为application/json
                                            data: JSON.stringify(imgArry),
                                            success: function (Result) {
                                                console.log(Result);
                                                if (Result.Status == "success") {
                                                    //
                                                    insertFn("https://www.kdddy.cn/Image/" + URL, "", "");
                                                } else {
                                                    // that.$message.error("上传失败");
                                                }
                                            },

                                            dataType: "json",
                                        });
                                    };
                                },
                                error(err) {
                                    console.log(err.message);
                                },
                            });
                        },
                    },
                },
                onChange: (editor) => {
                    form.News_Content = editor.getHtml();
                    console.log(form.News_Content);
                },
                onDestroyed(editor) {
                    editor.destroy();
                },
            };
            const editor = createEditor({
                selector: "#editor-container",
                html: "<p><br></p>",
                config: editorConfig,
                mode: 'default',
            });
            const toolbarConfig = {};
            const toolbar = createToolbar({
                editor: editor,
                selector: "#toolbar-container",
                config: toolbarConfig,
                mode: 'default',
            });
            const at = Object.seal(editor);
            editor1 = at;
        }
        // 获取新闻内容
        const EditNews = () => {
            const urlParams = new URLSearchParams(window.location.search);
            const Obtainaction = urlParams.get('action');
            const obtainNewsSerialNumber = urlParams.get('ObtainNews_SerialNumber');
            console.log('Action:', Obtainaction);
            console.log('ObtainNewsSerialNumber:', obtainNewsSerialNumber);
            // 获取新闻单条数据  编辑
            $.ajax({
                headers: {
                    "content-type": "application/x-www-form-urlencoded",
                },
                url: "https://service.essp.top/apiForMoHe/generalBusiness/generalQueryByTableNameWithOriginal",
                method: "post",
                data: {
                    Data: "news", //表名
                    Condition: "News_SerialNumber='" + obtainNewsSerialNumber + "'",
                },
                success: (res) => {
                    console.log(res);
                    Object.assign(form, res[0]);
                    if (res[0].News_Image_URL) {
                        imageUrl.value = res[0].News_Image_URL;
                        editor1.setHtml(res[0].News_Content);
                    }
                    console.log(form);
                },
                error: (err) => {
                    console.log(err)
                },
            });
        }
        //提交新闻数据
        // const submitNews = () => {

        //     if (form.type == '' || form.title == '' || form.content == '') {
        //         ElMessage.warning({ message: '请填充新闻信息！', duration: 1500 })
        //         return
        //     }

        //     //获取当前时间
        //     let time = parseTime(new Date())
        //     //参数结构
        //     const params = {
        //         Add: {
        //             news: [{
        //                 News_Category_SerialNumber: categoryNum,
        //                 News_Title: form.title,
        //                 News_Content: form.content,
        //                 News_Views_Count: '0',
        //                 News_Image_URL: imageUrl.value,
        //                 News_Publish_Datetime: time,
        //                 Creater_SerialNumber: '007',
        //                 Row_Status: '0',
        //                 Children: {
        //                     news_picture: [{
        //                         News_Piciture_URL: imageUrl.value,
        //                         Picture_Order: '0',
        //                         Create_Datetime: time,
        //                         Creater_SerialNumber: '007',
        //                         Row_Status: '0'
        //                     }]
        //                 }
        //             }]
        //         }
        //     }
        //     // 发送请求
        //     $.ajax({
        //         headers: {
        //             "content-type": "application/x-www-form-urlencoded",
        //         },
        //         url: "https://service.essp.top/apiForMoHe/generalBusiness/generalSave",
        //         method: "post",
        //         data: {
        //             Data: JSON.stringify(params),
        //         },
        //         success: (res) => {
        //             ElMessage.success({ message: '提交成功！', duration: 1400 })
        //             setTimeout(() => {
        //                 // window.location.href = './news_page.html'
        //             }, 1600)

        //         },
        //         error: (err) => {
        //             ElMessage.error({ message: '提交失败！', duration: 1500 })
        //             console.log('提交失败', err)
        //         },
        //     });
        // }
        const submitNews = () => {
            console.log(form);
            const urlParams = new URLSearchParams(window.location.search);
            const Obtainaction = urlParams.get('action');
            const obtainNewsSerialNumber = urlParams.get('ObtainNews_SerialNumber');
            console.log('Action:', Obtainaction);
            console.log('ObtainNewsSerialNumber:', obtainNewsSerialNumber);
            if (Obtainaction == "Add") {
                console.log('增加提交');
                //获取当前时间
                let time = parseTime(new Date())
                //参数结构
                const params = {
                    Add: {
                        news: [{
                            News_Category_SerialNumber: categoryNum,
                            News_Title: form.News_Title,
                            News_Content: form.News_Content,
                            News_Views_Count: '0',
                            News_Image_URL: imageUrl.value,
                            News_Publish_Datetime: time,
                            Creater_SerialNumber: '',
                            Row_Status: '0',
                            Children: {
                                news_picture: [{
                                    News_Piciture_URL: imageUrl.value,
                                    Picture_Order: '0',
                                    Create_Datetime: time,
                                    Creater_SerialNumber: '007',
                                    Row_Status: '0'
                                }]
                            }
                        }]
                    }
                }
                // 发送请求
                $.ajax({
                    headers: {
                        "content-type": "application/x-www-form-urlencoded",
                    },
                    url: "https://service.essp.top/apiForMoHe/generalBusiness/generalSave",
                    method: "post",
                    data: {
                        Data: JSON.stringify(params),
                    },
                    success: (res) => {
                        ElMessage.success({ message: '提交成功！', duration: 1400 })
                        setTimeout(() => {
                            // window.location.href = './news_page.html'
                        }, 1600)

                    },
                    error: (err) => {
                        ElMessage.error({ message: '提交失败！', duration: 1500 })
                        console.log('提交失败', err)
                    },
                });

            } else if (Obtainaction == "Modify") {
                console.log('修改提交');
                $.ajax({
                    headers: {
                        "content-type": "application/x-www-form-urlencoded",
                    },
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    method: "post",
                    data: {
                        Data: 'news',
                        Condition: "News_SerialNumber='" + form.News_SerialNumber + "'"
                    },
                    success: (res) => {
                        console.log('修改成功', res);
                        let a = new Array()
                        a.push(res[0])
                        let lnews_picture = new Object
                        lnews_picture.news_picture = a
                        let a11 = new Array()
                        a11.push(lnews_picture)
                        console.log(form);
                        // form.Children = a11
                        let Array11 = new Array()
                        Array11.push(form)
                        let lnews = new Object
                        lnews.news = Array11
                        let aaa = new Object()
                        aaa.Modify = lnews
                        console.log(aaa);
                        // return
                        $.ajax({
                            headers: {
                                "content-type": "application/x-www-form-urlencoded",
                            },
                            url: `${mh}/generalBusiness/generalSave`,
                            method: "post",
                            data: {
                                Data: JSON.stringify(aaa),
                            },
                            success: (res) => {
                                ElMessage.success({ message: '提交成功！', duration: 1400 })
                                setTimeout(() => {
                                    // window.location.href = './news_page.html'
                                }, 1600)
                            },
                            error: (err) => {
                                ElMessage.error({ message: '提交失败！', duration: 1500 })
                                console.log('提交失败', err)
                            },
                        });

                    },
                    error: (err) => {
                        ElMessage.error({ message: '提交失败！', duration: 1500 })
                        console.log('提交失败', err)
                    },
                });
            }
        }
        //限制图片类型及大小
        const beforeAvatarUpload = (rawFile) => {
            const validTypes = ['image/jpeg', 'image/png']
            if (!validTypes.includes(rawFile.type)) {
                ElMessage.error({ message: '仅支持 JPG / PNG 格式的图片', duration: 1500 })
                return false
            } else if (rawFile.size / 1024 / 1024 > 8) {
                ElMessage.error({ message: '图片大小不能超过8MB！', duration: 1500 })
                return false
            }
            return true
        }
        //更改图片的操作
        const handleImgChange = (file) => {
            const reader = new FileReader()
            // 在 onload 回调中处理结果
            reader.onload = (e) => {
                let res = e.target.result // 转化为base64的结果
                //上传
                uploadImg(res)
            };
            reader.readAsDataURL(file.raw) // 开始读取文件
        }
        // 上传图片的请求
        const uploadImg = (params) => {
            $.ajax({
                headers: {
                    "content-type": "application/json",
                },
                url: "https://service.essp.top/apiForMoHe/generalBusiness/generalSaveFilesAsImage",
                method: "post",
                data: JSON.stringify({
                    Data: params
                }),
                success: (res) => {
                    //图片回显路径
                    imageUrl.value = `https://service.essp.top/mh/Image/${res.FileName}`
                    ElMessage.success({ message: '上传成功', duration: 1500 })
                },
                error: (err) => {
                    console.log('上传失败', err);
                    ElMessage.error({ message: '上传失败', duration: 1500 })
                },
            });
        }
        return {
            form,
            imageUrl,
            newsType,
            typeChange,
            beforeAvatarUpload,
            handleImgChange,
            submitNews,
            EditNews
        }
    }
});


//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus);
app.mount("#app");
